/**
 * operation_test.js - 电机试验数据管理模块
 */

// API基本路径
const OPERATION_TEST_API_BASE = '/api/feibiao/operation-test';
let currentTestPage = 0;
let testPageSize = 10;
let currentTestSearchKeyword = '';

// 加载电机试验数据列表
function loadOperationTestList(page = 0, size = 10) {
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">数据加载中...</div>';
    
    // 保存当前页码
    currentTestPage = page;
    testPageSize = size;
    
    // 构建完整URL，并记录到控制台
    const apiUrl = `${OPERATION_TEST_API_BASE}?page=${page}&size=${size}`;
    
    fetch(apiUrl)
        .then(response => {
            if (!response.ok) {
                return response.text().then(text => {
                    console.error('API请求失败:', response.status, response.statusText, text);
                    try {
                        const error = JSON.parse(text);
                        throw new Error(`服务器错误 (${response.status}): ${error.message || error.error || response.statusText}`);
                    } catch (e) {
                        if (e instanceof SyntaxError) {
                            throw new Error(`服务器错误 (${response.status}): ${text || response.statusText}`);
                        }
                        throw e;
                    }
                });
            }
            return response.json();
        })
        .then(data => {
            renderOperationTestTable(data);
        })
        .catch(error => {
            console.error('获取电机试验数据失败:', error);
            mainContent.innerHTML = `
                <div class="error-container">
                    <h2>加载数据失败</h2>
                    <p>错误信息: ${error.message}</p>
                    <p>请求URL: ${window.location.origin}${apiUrl}</p>
                    <p>可能的原因:</p>
                    <ul>
                        <li>后端服务未启动或无法访问</li>
                        <li>数据库表结构与实体类不匹配</li>
                        <li>API路径配置不正确(当前路径: ${OPERATION_TEST_API_BASE})</li>
                        <li>后端Controller未正确映射该路径</li>
                        <li>外键约束问题: 检查am_archives_base表中是否有电机记录</li>
                        <li>实体类与表结构字段不匹配</li>
                    </ul>
                    <div class="test-actions">
                        <button class="btn btn-info" onclick="testOperationTestAPI()">测试API</button>
                    </div>
                    <div class="error-actions">
                        <button class="btn btn-primary" onclick="loadOperationTestList()">重试</button>
                        <button class="btn btn-default" onclick="loadFeiBiaoContent('base')">返回电机基本信息</button>
                    </div>
                </div>
            `;
            showMessage('获取电机试验数据失败: ' + error.message, 'error');
        });
}

// 测试API可用性
function testOperationTestAPI() {
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = `
        <div class="content-header">
            <h2 class="content-title">电机试验数据API测试</h2>
            <div class="header-actions">
                <button class="btn btn-default" onclick="loadOperationTestList()">返回列表</button>
            </div>
        </div>
        
        <div class="api-test-container">
            <div class="test-status">正在测试API端点，请稍候...</div>
            <div id="testResults" class="test-results"></div>
        </div>
    `;
    
    const testResults = document.getElementById('testResults');
    
    // 测试多个API端点
    const endpoints = [
        { url: OPERATION_TEST_API_BASE, method: 'GET', name: '列表查询(主接口)' },
        { url: '/api/feibiao/operation-test?page=0&size=10', method: 'GET', name: '列表查询(带参数)' },
        { url: '/api/feibiao/operation', method: 'GET', name: '运行数据接口(测试对比)' },
        { url: '/api/feibiao/motor-base', method: 'GET', name: '电机基本信息接口(测试对比)' }
    ];
    
    let completedTests = 0;
    
    // 按顺序测试各个端点
    endpoints.forEach((endpoint, index) => {
        const fullUrl = window.location.origin + endpoint.url;
        console.log(`测试API端点: ${fullUrl}`);
        
        fetch(endpoint.url, { method: endpoint.method })
            .then(response => {
                const statusClass = response.ok ? 'success' : 'error';
                const statusText = response.ok ? '成功' : '失败';
                
                return response.text().then(text => {
                    let responseDetails = '';
                    if (!response.ok) {
                        let errorMessage = '';
                        try {
                            // 尝试解析JSON错误信息
                            const errorJson = JSON.parse(text);
                            errorMessage = errorJson.message || errorJson.error || text;
                        } catch (e) {
                            // 如果不是JSON，直接使用文本
                            errorMessage = text;
                        }
                        
                        responseDetails = `
                            <div class="error-details">
                                <p><strong>状态码:</strong> ${response.status}</p>
                                <p><strong>错误详情:</strong> ${errorMessage || '无详细信息'}</p>
                            </div>
                        `;
                    } else {
                        let responseData = '';
                        try {
                            const jsonData = JSON.parse(text);
                            responseData = JSON.stringify(jsonData, null, 2).substring(0, 150) + '...';
                        } catch (e) {
                            responseData = text.substring(0, 150) + '...';
                        }
                        
                        responseDetails = `
                            <div class="success-details">
                                <p><strong>响应预览:</strong></p>
                                <pre class="response-preview">${responseData}</pre>
                            </div>
                        `;
                    }
                    
                    testResults.innerHTML += `
                        <div class="test-result ${statusClass}">
                            <div class="test-name">${endpoint.name}</div>
                            <div class="test-url">${endpoint.method} ${endpoint.url}</div>
                            <div class="test-status">状态: ${response.status} ${response.statusText} - ${statusText}</div>
                            ${responseDetails}
                        </div>
                    `;
                    
                    completedTests++;
                    if (completedTests === endpoints.length) {
                        const testStatus = document.querySelector('.test-status');
                        testStatus.textContent = '测试完成，请检查各端点响应情况';
                        
                        // 添加总结和建议
                        testResults.innerHTML += `
                            <div class="test-summary">
                                <h4>API测试总结与建议</h4>
                                <p>根据测试结果，您可以采取以下措施：</p>
                                <ol>
                                    <li>检查后端Controller中的@RequestMapping路径配置</li>
                                    <li>确认后端API路径是否为 '/api/feibiao/operation-test'</li>
                                    <li>检查运行数据接口与基本信息接口是否正常工作</li>
                                    <li>可能需要将实体类和Controller中的路径修改为 'operation-test' 而非 'operation_test'</li>
                                    <li>确认Controller类是否正确注册并扫描到</li>
                                </ol>
                            </div>
                        `;
                    }
                });
            })
            .catch(error => {
                testResults.innerHTML += `
                    <div class="test-result error">
                        <div class="test-name">${endpoint.name}</div>
                        <div class="test-url">${endpoint.method} ${endpoint.url}</div>
                        <div class="test-status">状态: 请求失败 - ${error.message}</div>
                        <div class="error-details">
                            <p>请求无法完成，可能是网络问题或服务器未运行</p>
                        </div>
                    </div>
                `;
                
                completedTests++;
                if (completedTests === endpoints.length) {
                    const testStatus = document.querySelector('.test-status');
                    testStatus.textContent = '测试完成，请检查各端点响应情况';
                }
            });
    });
}

// 渲染电机试验数据表格
function renderOperationTestTable(data) {
    const mainContent = document.getElementById('mainContent');
    let html = `
        <div class="content-header">
            <h2 class="content-title">电机试验数据管理</h2>
            <div class="header-actions">
                <button class="btn btn-primary" onclick="showOperationTestForm()"></i> 新增</button>
            </div>
        </div>
        <div class="content-toolbar">
            <div class="search-box">
                <input type="text" class="search-input" id="operationTestSearchInput" placeholder="输入电机ID搜索..." value="${currentTestSearchKeyword}">
                <button class="search-btn" onclick="searchOperationTest()">搜索</button>
                ${currentTestSearchKeyword ? '<button class="btn btn-default" onclick="clearTestSearch()">返回列表</button>' : ''}
            </div>
        </div>
        <div class="table-responsive">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>电机ID</th>
                        <th>试验类型</th>
                        <th>试验时间</th>
                        <th>效率(%)</th>
                        <th>功率因数</th>
                        <th>扭矩(N·m)</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
    `;

    if (data.content && data.content.length > 0) {
        data.content.forEach(test => {
            html += `
                <tr>
                    <td>${test.testId}</td>
                    <td>${test.motorId}</td>
                    <td>${test.testType}</td>
                    <td>${formatDateTime(test.testTime)}</td>
                    <td>${formatNumber(test.efficiency)}</td>
                    <td>${formatNumber(test.powerFactor)}</td>
                    <td>${formatNumber(test.torque)}</td>
                    <td class="table-actions">
                        <a href="javascript:void(0)" onclick="viewOperationTest(${test.testId})">查看</a>
                        <a href="javascript:void(0)" onclick="editOperationTest(${test.testId})">编辑</a>
                        <a href="javascript:void(0)" class="delete" onclick="deleteOperationTest(${test.testId})">删除</a>
                    </td>
                </tr>
            `;
        });
    } else {
        html += `
            <tr>
                <td colspan="8" class="text-center">暂无数据</td>
            </tr>
        `;
    }

    html += `
                </tbody>
            </table>
        </div>
    `;

    // 修改分页控件样式，与archivesoperation.js保持一致
    if (data.totalPages > 0) {
        html += `
            <ul class="pagination">
                <li class="${currentTestPage <= 0 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${currentTestPage <= 0 ? 'void(0)' : 'loadOperationTestList(' + (currentTestPage - 1) + ', ' + testPageSize + ')'}">上一页</a>
                </li>
        `;
        
        // 页码
        for (let i = 0; i < data.totalPages; i++) {
            if (i === currentTestPage) {
                html += `<li class="active"><a href="javascript:void(0)">${i + 1}</a></li>`;
            } else {
                html += `<li><a href="javascript:void(0)" onclick="loadOperationTestList(${i}, ${testPageSize})">${i + 1}</a></li>`;
            }
        }
        
        html += `
                <li class="${currentTestPage >= data.totalPages - 1 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${currentTestPage >= data.totalPages - 1 ? 'void(0)' : 'loadOperationTestList(' + (currentTestPage + 1) + ', ' + testPageSize + ')'}">下一页</a>
                </li>
            </ul>
        `;
    }

    mainContent.innerHTML = html;
}

// 显示电机试验数据表单
function showOperationTestForm(test = null) {
    const mainContent = document.getElementById('mainContent');
    const isEdit = test !== null;

    mainContent.innerHTML = `
        <div class="content-header">
            <h2 class="content-title">${isEdit ? '编辑' : '新增'}电机试验数据</h2>
            <div class="header-actions">
                <button class="btn btn-default" onclick="loadOperationTestList(${currentTestPage}, ${testPageSize})">返回列表</button>
            </div>
        </div>
        <div class="form-container">
            <form id="operationTestForm" onsubmit="return submitOperationTestForm(event)">
                ${isEdit ? `<input type="hidden" id="testId" value="${test.testId}">` : ''}
                <div class="form-group">
                    <label for="motorId">电机ID:</label>
                    <input type="text" id="motorId" name="motorId" class="form-control" required
                           value="${isEdit ? test.motorId : ''}">
                    <small class="form-text">必须是已存在的电机ID</small>
                </div>
                <div class="form-group">
                    <label for="testType">试验类型:</label>
                    <select id="testType" name="testType" class="form-control" required>
                        <option value="">-- 请选择 --</option>
                        <option value="出厂试验" ${isEdit && test.testType === '出厂试验' ? 'selected' : ''}>出厂试验</option>
                        <option value="定期试验" ${isEdit && test.testType === '定期试验' ? 'selected' : ''}>定期试验</option>
                        <option value="故障后试验" ${isEdit && test.testType === '故障后试验' ? 'selected' : ''}>故障后试验</option>
                        <option value="其他" ${isEdit && (test.testType !== '出厂试验' && test.testType !== '定期试验' && test.testType !== '故障后试验') ? 'selected' : ''}>其他</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="testTime">试验时间:</label>
                    <input type="datetime-local" id="testTime" name="testTime" class="form-control" required
                           value="${isEdit ? formatDateTimeForInput(test.testTime) : ''}">
                </div>
                <div class="form-group">
                    <label for="efficiency">效率(%):</label>
                    <input type="number" id="efficiency" name="efficiency" class="form-control" step="0.01" min="0" max="100" required
                           value="${isEdit ? test.efficiency : ''}">
                </div>
                <div class="form-group">
                    <label for="powerFactor">功率因数:</label>
                    <input type="number" id="powerFactor" name="powerFactor" class="form-control" step="0.01" min="0" max="1" required
                           value="${isEdit ? test.powerFactor : ''}">
                </div>
                <div class="form-group">
                    <label for="torque">扭矩(N·m):</label>
                    <input type="number" id="torque" name="torque" class="form-control" step="0.01" min="0" required
                           value="${isEdit ? test.torque : ''}">
                </div>
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">${isEdit ? '更新' : '保存'}</button>
                    <button type="button" class="btn btn-default" onclick="loadOperationTestList(${currentTestPage}, ${testPageSize})">取消</button>
                </div>
            </form>
        </div>
    `;
}

// 查看电机试验数据详情
function viewOperationTest(id) {
    fetch(`${OPERATION_TEST_API_BASE}/${id}`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`服务器错误 (${response.status}): ${response.statusText}`);
            }
            return response.json();
        })
        .then(test => {
            showOperationTestDetail(test);
        })
        .catch(error => {
            console.error('获取电机试验数据详情失败:', error);
            showMessage('获取电机试验数据详情失败: ' + error.message, 'error');
        });
}

// 显示电机试验数据详情 - 修改为与archivesoperation.js一致的样式
function showOperationTestDetail(test) {
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = `
        <div class="content-header">
            <h2 class="content-title">电机试验数据详情</h2>
            <div class="header-actions">
                <button class="btn btn-default" onclick="loadOperationTestList(${currentTestPage}, ${testPageSize})"><i class="fa fa-list"></i> 返回列表</button>
            </div>
        </div>
        <div class="data-detail">
            <div class="detail-group"><label>ID:</label><div>${test.testId || '--'}</div></div>
            <div class="detail-group"><label>电机ID:</label><div>${test.motorId || '--'}</div></div>
            <div class="detail-group"><label>试验类型:</label><div>${test.testType || '--'}</div></div>
            <div class="detail-group"><label>试验时间:</label><div>${formatDateTime(test.testTime) || '--'}</div></div>
            <div class="detail-group"><label>效率(%):</label><div>${formatNumber(test.efficiency) || '--'}</div></div>
            <div class="detail-group"><label>功率因数:</label><div>${formatNumber(test.powerFactor) || '--'}</div></div>
            <div class="detail-group"><label>扭矩(N·m):</label><div>${formatNumber(test.torque) || '--'}</div></div>
            <div class="detail-actions">
                <button class="btn btn-primary" onclick="editOperationTest(${test.testId})"><i class="fa fa-edit"></i> 编辑</button>
                <button class="btn btn-danger" onclick="deleteOperationTest(${test.testId})"><i class="fa fa-trash"></i> 删除</button>
                <button class="btn btn-default" onclick="loadOperationTestList(${currentTestPage}, ${testPageSize})"><i class="fa fa-list"></i> 返回列表</button>
            </div>
        </div>
    `;
}

// 提交电机试验数据表单
function submitOperationTestForm(event) {
    event.preventDefault();
    
    // 获取表单数据
    const motorId = document.getElementById('motorId').value.trim();
    const testType = document.getElementById('testType').value;
    const testTime = document.getElementById('testTime').value;
    const efficiency = document.getElementById('efficiency').value;
    const powerFactor = document.getElementById('powerFactor').value;
    const torque = document.getElementById('torque').value;
    
    // 数据验证
    if (!motorId) {
        showMessage('请输入电机ID', 'error');
        return false;
    }
    
    if (!testType) {
        showMessage('请选择试验类型', 'error');
        return false;
    }
    
    if (!testTime) {
        showMessage('请选择试验时间', 'error');
        return false;
    }
    
    // 验证数值范围
    const validateNumber = (value, fieldName, min, max) => {
        if (value === '' || isNaN(value) || parseFloat(value) < min || parseFloat(value) > max) {
            showMessage(`${fieldName}必须在${min}到${max}之间`, 'error');
            return false;
        }
        return true;
    };
    
    if (!validateNumber(efficiency, '效率', 0, 100)) return false;
    if (!validateNumber(powerFactor, '功率因数', 0, 1)) return false;
    if (!validateNumber(torque, '扭矩', 0, 10000)) return false;
    
    const formData = {
        motorId: motorId,
        testType: testType,
        testTime: testTime,
        efficiency: parseFloat(efficiency),
        powerFactor: parseFloat(powerFactor),
        torque: parseFloat(torque),
        testDate: testTime // 冗余字段，与testTime保持一致
    };
    
    const testId = document.getElementById('testId');
    const isEdit = testId !== null && testId.value;
    const url = isEdit ? `${OPERATION_TEST_API_BASE}/${testId.value}` : OPERATION_TEST_API_BASE;
    const method = isEdit ? 'PUT' : 'POST';
    
    fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
    })
    .then(response => {
        if (!response.ok) {
            return response.text().then(text => {
                throw new Error(`服务器错误 (${response.status}): ${text || response.statusText}`);
            });
        }
        return response.json();
    })
    .then(data => {
        showMessage(`${isEdit ? '更新' : '新增'}电机试验数据成功`, 'success');
        loadOperationTestList(currentTestPage, testPageSize);
    })
    .catch(error => {
        console.error(`${isEdit ? '更新' : '新增'}电机试验数据失败:`, error);
        showMessage(`${isEdit ? '更新' : '新增'}电机试验数据失败: ` + error.message, 'error');
    });
    
    return false;
}

// 编辑电机试验数据
function editOperationTest(id) {
    fetch(`${OPERATION_TEST_API_BASE}/${id}`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`服务器错误 (${response.status}): ${response.statusText}`);
            }
            return response.json();
        })
        .then(test => {
            showOperationTestForm(test);
        })
        .catch(error => {
            console.error('获取电机试验数据详情失败:', error);
            showMessage('获取电机试验数据详情失败: ' + error.message, 'error');
        });
}

// 删除电机试验数据
function deleteOperationTest(id) {
    if (confirm('确定要删除这条电机试验数据吗？此操作不可恢复。')) {
        fetch(`${OPERATION_TEST_API_BASE}/${id}`, {
            method: 'DELETE'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`服务器错误 (${response.status}): ${response.statusText}`);
            }
            showMessage('删除电机试验数据成功', 'success');
            loadOperationTestList(currentTestPage, testPageSize);
        })
        .catch(error => {
            console.error('删除电机试验数据失败:', error);
            showMessage('删除电机试验数据失败: ' + error.message, 'error');
        });
    }
}

// 清除搜索
function clearTestSearch() {
    document.getElementById('operationTestSearchInput').value = '';
    currentTestSearchKeyword = '';
    currentTestPage = 0;
    loadOperationTestList(0, testPageSize);
}

// 搜索电机试验数据
function searchOperationTest() {
    const keyword = document.getElementById('operationTestSearchInput').value.trim();
    currentTestSearchKeyword = keyword;
    currentTestPage = 0;
    
    if (!keyword) {
        loadOperationTestList(0, testPageSize);
        return;
    }
    
    // 显示加载中
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">数据加载中...</div>';
    
    fetch(`${OPERATION_TEST_API_BASE}/by-motor?motorId=${encodeURIComponent(keyword)}`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`搜索失败 (${response.status}): ${response.statusText}`);
            }
            return response.json();
        })
        .then(data => {
            // 处理返回的数据（预期是数组）
            const content = Array.isArray(data) ? data : [];
            
            // 将数据转换为分页格式以便复用现有的表格渲染函数
            const pageData = {
                content: content,
                totalPages: 1,
                number: 0,
                size: content.length,
                first: true,
                last: true,
                totalElements: content.length
            };
            
            // 显示搜索结果
            renderOperationTestTable(pageData);
            
            // 显示搜索信息
            const searchInfo = document.createElement('div');
            searchInfo.className = 'search-result-info';
            searchInfo.innerHTML = `搜索"${keyword}": 找到 ${content.length} 条记录`;
            document.querySelector('.content-toolbar').after(searchInfo);
        })
        .catch(error => {
            console.error('搜索电机试验数据失败:', error);
            showMessage('搜索电机试验数据失败: ' + error.message, 'error');
            
            // 搜索失败时显示空结果
            renderOperationTestTable({
                content: [],
                totalPages: 0,
                number: 0,
                size: testPageSize,
                first: true,
                last: true,
                totalElements: 0
            });
        });
}

// 格式化日期时间
function formatDateTime(dateTimeStr) {
    if (!dateTimeStr) return '-';
    const date = new Date(dateTimeStr);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
}

// 格式化日期时间为input datetime-local的值
function formatDateTimeForInput(dateTimeStr) {
    if (!dateTimeStr) return '';
    const date = new Date(dateTimeStr);
    return date.toISOString().slice(0, 16);
}

// 格式化数字，保留2位小数
function formatNumber(num) {
    if (num === null || num === undefined) return '--';
    return parseFloat(num).toFixed(2);
}

// 将函数暴露给全局
if (typeof window !== 'undefined') {
    window.loadOperationTestList = loadOperationTestList;
    window.renderOperationTestTable = renderOperationTestTable;
    window.showOperationTestForm = showOperationTestForm;
    window.viewOperationTest = viewOperationTest;
    window.showOperationTestDetail = showOperationTestDetail;
    window.submitOperationTestForm = submitOperationTestForm;
    window.editOperationTest = editOperationTest;
    window.deleteOperationTest = deleteOperationTest;
    window.searchOperationTest = searchOperationTest;
    window.clearTestSearch = clearTestSearch;
    window.testOperationTestAPI = testOperationTestAPI;
} 